<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\timer\model\dealer;

use app\common\model\dealer\Order as OrderModel;
use app\timer\model\dealer\Setting as DealerSettingModel;
use app\common\enum\order\OrderStatus as OrderStatusEnum;

/**
 * 分销商订单模型
 * Class Apply
 * @package app\timer\model\dealer
 */
class Order extends OrderModel
{
    /**
     * 获取未结算的分销订单
     * @param int $storeId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUnSettledList(int $storeId)
    {
        // 可结算的订单条件
        $filter = [
            ['order.is_delete', '=', 0],
            ['order.order_status', '=', OrderStatusEnum::COMPLETED]
        ];
        // 佣金结算天数
        $filter[] = ['order.receipt_time', '<=', DealerSettingModel::getSettleTerm($storeId)];
        // 获取订单列表记录
        return $this->alias('m')
            ->field(['m.*'])
            ->with(['order' => ['goods' => ['refund']]])
            ->join('order', 'm.order_id = order.order_id')
            ->where($filter)
            ->where('m.is_invalid', '=', 0)
            ->where('m.is_settled', '=', 0)
            ->where('m.store_id', '=', $storeId)
            ->select();
    }

    /**
     * 获取失效的分销订单ID集
     * @param int $storeId
     * @return array
     */
    public function getInvalidOrderIds(int $storeId)
    {
        // 失效订单条件
        $filter = [
            ['order.is_delete', '=', 1],
            ['order.order_status', '=', OrderStatusEnum::CANCELLED]
        ];
        return $this->alias('m')
            ->join('order', 'm.order_id = order.order_id')
            ->whereOr($filter)
            ->where('m.is_invalid', '=', 0)
            ->where('m.is_settled', '=', 0)
            ->where('m.store_id', '=', $storeId)
            ->column('m.order_id');
    }

    /**
     * 标记订单已失效(批量)
     * @param array $orderIds
     * @return bool
     */
    public function setInvalid(array $orderIds)
    {
        return static::updateBase(['is_invalid' => 1], [['order_id', 'in', $orderIds]]);
    }
}